package aplications.android;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Displays and calculates the histogram of one image.
 */
public class ColorDetection extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	 super.onCreate(savedInstanceState);
    	 setContentView(R.layout.colordetection);
    	 
    	 TextView tv = (TextView) findViewById(R.id.textView1);
    	 
    	 Bundle bundle = getIntent().getExtras();
    	
    	 if(bundle!=null)
    	 {
	    	 if(bundle.getString("pathImage")!=null)
	    	 {
	    		 Bitmap Imag = BitmapFactory.decodeFile(bundle.getString("pathImage"));
	    		 int color[] = Histogram(Imag);
	    		
	    		 ImageView imageV = (ImageView)findViewById(R.id.imageView1);
	    		 imageV.setImageBitmap(Imag);  
	    		 tv.setText("Ancho: " + Imag.getWidth() + "\n" +
	    				 	"Alto: " + Imag.getHeight() + "\n" +
	    				 	"Color: ("+ color[0] + "," + color[1] + "," + color[2] + ")");
	    	 }
    	 }
    	 else
    		 tv.setText("No hay color");
    }
    
    /** Return the color of the image */
    private int[] Histogram(Bitmap bmp)
    {
    	int R[]= new int[256];
    	int G[]= new int[256];
    	int B[]= new int[256];
    	
    	int Rmax = 0;
    	int Gmax = 0;
    	int Bmax = 0;
    	
    	int picw = bmp.getWidth(); 			
    	int pich = bmp.getHeight();
		 
	    int[] pix = new int[picw * pich];
	    bmp.getPixels(pix, 0, picw, 0, 0, picw, pich);
	    
	    for (int y = 0; y < pich; y++)
	    {
		    for (int x = 0; x < picw; x++)
		    {
			    int index = y * picw + x;
			    
//			    int A =(pix[index] >> 24) & 0xff;		//A
			    int r =(pix[index] >> 16) & 0xff;		//R
		    	int g =(pix[index] >> 8) & 0xff;		//G
	    		int b =pix[index] & 0xff;				//B
	    		
	    		R[r]++;
	    		if(R[r] > Rmax) Rmax=r;
	    			
	    		G[g]++;
	    		if(G[g] > Gmax) Gmax=g;
	    			
	    		B[b]++;
	    		if(B[b] > Bmax) Bmax=b;
		    }
	    }
	    int color[] = {Rmax,Gmax,Bmax};
	    return color;
    }
}